package js.web.center.netty.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import js.web.center.netty.client.iface.IJsWebClientSDK;
import js.web.center.netty.code.JsWebSocketDecoder;
import js.web.center.netty.code.JsWebSocketEncoder;

public abstract class JsWebClientSDK implements IJsWebClientSDK{
	public JsWebClientHandler jsWebClientHandler=null;
	public ChannelHandlerContext channelHandlerContext=null;
	public String host;
	public int port;
	/** 
     * 连接服务器 
     *  
     * @param port 
     * @param host 
     * @throws Exception 
     */  
    public void connect(int port, String host) throws Exception {  
        EventLoopGroup group = new NioEventLoopGroup();  
        this.port=port;
        this.host=host;
        try {  
            Bootstrap bootStrap = new Bootstrap();  
            bootStrap.group(group)
            .channel(NioSocketChannel.class)
            .option(ChannelOption.TCP_NODELAY, true)  
            .handler(new JsWebChannelHandler(this));  
            ChannelFuture channelFuture = bootStrap.connect(host, port).sync();  
            channelFuture.channel().closeFuture().sync();  
        } finally {  
            group.shutdownGracefully();  
        }  
    }  
    /** 
     * 网络事件处理器 
     */  
    private class JsWebChannelHandler extends ChannelInitializer<SocketChannel> {  
    	private IJsWebClientSDK clientSDK;
    	public JsWebChannelHandler(IJsWebClientSDK clientSDK) {
    		this.clientSDK=clientSDK;
		}
        @Override  
        protected void initChannel(SocketChannel ch) throws Exception {  
            ch.pipeline().addLast(new JsWebSocketEncoder());  
            ch.pipeline().addLast(new JsWebSocketDecoder());  
            jsWebClientHandler=new JsWebClientHandler(this.clientSDK);
            ch.pipeline().addLast(jsWebClientHandler);  
        }  
    }
	@Override
	public ChannelHandlerContext context() {
		return this.channelHandlerContext;
	}
	@Override
	public void send(byte[] bytes) {
		this.jsWebClientHandler.sendMsg(bytes);
	}
}
